// 让node能连接上mysql
const mysql = require('mysql')
const config = require('../config')

//创建线程池
const pool = mysql.createPool({
  host: config.database.HOST,
  user: config.database.USERNAME,
  password: config.database.PASSWORD,
  database: config.database.DATABASE,
  port: config.database.PORT
})

// 连接数据库，执行sql语句
const allService = {
  query: function(sql, values) {
    return new Promise((resolve, reject) => {
      pool.getConnection((err, connection) => { // 连接数据库
        console.log(err);
        if (err) {
          reject(err)
        } else { // 连接成功
          
          connection.query(sql, values, (err, rows) => { // 执行sql语句
            if (err) {
              console.log(1111111, err);
              reject(err)
            } else { // sql语句执行成功
              resolve(rows)
            }
            connection.release() // 断开连接
          })
        }
      })
    })
  }
}

// 登录
const userLogin = (username, password) => {
  let _sql = `select * from users where username="${username}" and password="${password}";`
  return allService.query(_sql)
}

// 查找
const userFind = (username) => {
  let _sql = `select * from users where username="${username}";`
  return allService.query(_sql)
}




// 注册
const userRegister = (values) => {
  let _sql = `insert into users set username=?,password=?,nickname=?,head_img=?;`
  return allService.query(_sql, values)
}

//根据分类查找对应的习惯列表
// const findHabitByType = (habit_lable) => {
//   let _sql = `select * from addhabit where habit_lable="${habit_lable}";`
//   return allService.query(_sql)
// }

//查找全部的习惯
const findAllHabit = () => {
  let _sql = `select * from addhabit ;`
  return allService.query(_sql)
}

//添加习惯
const addHabit = (values) => {
  let _sql = `insert into addhabit set title=?,habit_lable=?,color=?,icon_class=?,add_time=?;`
  return allService.query(_sql,values)
}

//删除习惯 DELETE FROM users WHERE id = 1
const deleteHabit = (id) => {
  let _sql = `delete from addhabit where id="${id}";`
  return allService.query(_sql)
}

module.exports = {
  userLogin,
  userFind,
  userRegister,
  // findHabitByType,
  addHabit,
  findAllHabit,
  deleteHabit
}